package com.nio.www.ex1;

import java.nio.CharBuffer;

/**
 * @author 新技术软件：汪洋
 *
 * Buffer fill/drain example.
 * This code uses the simplest
 * means of filling and draining a buffer:
 * one element at a time.
 **/
public class BufferFillDrain {
    public static void main (String [] argv) throws Exception {
        CharBuffer buffer = CharBuffer.allocate (100);
        while (fillBuffer (buffer)) {
            buffer.flip( );
            drainBuffer (buffer);
            buffer.clear( );
        }
        /**如果缓冲区存有比数组能容纳的数量更多的数据，您可以重复利用如下文所示的程序块进行读取
        char [] smallArray = new char [10];
        while (buffer.hasRemaining( )) {
            int length = Math.min (buffer.remaining( ), smallArray.length);
            buffer.get (smallArray, 0, length);
            processData (smallArray, length);
        }**/
    }

    private static int index = 0;

    private static void drainBuffer (CharBuffer buffer) {
        while (buffer.hasRemaining( )) {
            System.out.print (buffer.get( ));
        }
        System.out.println ("");
    }

    private static boolean fillBuffer (CharBuffer buffer) {
        if (index >= strings.length) {
            return (false);
        }
        String string = strings [index++];
        for (int i = 0; i < string.length( ); i++) {
            buffer.put (string.charAt (i));
        }
        return (true);
    }

    private static String [] strings = {
            "A random string value",
            "The product of an infinite number of monkeys",
            "Hey hey we're the Monkees",
            "Opening act for the Monkees: Jimi Hendrix",
            "'Scuse me while I kiss this fly",// Sorry Jimi ;-)
            "Help Me! Help Me!", };
}